import { Component, OnInit, Output, EventEmitter, Input } from "@angular/core";
import { Observable, observable, Subscription } from "rxjs";
import { ActivatedRoute } from "@angular/router";
import { FileService } from "../service/file.service";
import { FileUploader } from "ng2-file-upload";
import { Location } from "@angular/common";
declare var $: JQueryStatic;

import { ComponentChoiceService } from "../service/component-choice.service";
import { TextService } from "../service/text.service";
import { SafenlService } from "../service/safenl.service";
import { minunsatRes } from "../entity/minunsatRes";
// import { UploadService } from '../service/upload.service';

@Component({
  selector: "app-topbar",
  templateUrl: "./topbar.component.html",
  styleUrls: ["./topbar.component.css"]
})
export class TopbarComponent implements OnInit {
  @Input() projectName: string;
  @Output() openEvent = new EventEmitter<string[]>();
  @Output() getCCSL = new EventEmitter<string[]>();
  @Output() SMTEvent = new EventEmitter<boolean>();
  @Output() ToCCSLEvent = new EventEmitter<boolean>();
  @Output() importEvent = new EventEmitter<boolean>();

  subscription: Subscription;
  projects: string[];
  isFileExist: boolean = false;
  isCCSL: boolean = false;
  smtCheck:boolean = false;
  safenlConsistent: boolean = false;

  interval;
  interval1;
  editorType;
  constructor(
    private route: ActivatedRoute,
    private fileService: FileService,
    private textService: TextService,
    private safenlService: SafenlService,
    private location: Location,
    public component_choice_service: ComponentChoiceService
  ) {
    safenlService.isCCSLEmmited$.subscribe(isCCSL => {
      this.isCCSL = isCCSL;
    });
    
    var data = {
      username: "user_RT",
    }
    document.cookie = (JSON.stringify(data))

		if(document.cookie != ''){
			console.log(document.cookie)
			this.userName = jQuery.parseJSON(document.cookie)['username']
		}else{
      this.userName = ''
    }
  }
  ngOnInit() {}

  projectAddress: string;
  userName: string
  /*  version: string;*/

  newFile(): void {
    this.fileService.newProject(true);
    this.isFileExist = true;
  }

  openSafeNL() {
    this.fileService.searchProject(this.userName).subscribe(projects => {
      this.projects = projects;
      this.openEvent.emit(projects);
      this.isFileExist = true;
    });
  }

  importSafeNL(){
    this.importEvent.emit(true);
    this.isFileExist = true;
  }

  saveSafeNL() {
    var result: boolean;
    console.log(this.fileService.version)
    this.safenlService.safeNL = this.textService.getText();
    this.fileService.saveSafeNL(this.userName, this.projectName, this.fileService.version, this.safenlService.safeNL).subscribe(version => {
      if(version){
        alert("save succeed!");
        console.log(this.fileService.version)
        this.fileService.version = version[0];
        this.isCCSL = false;
        this.isFileExist = false;
      }else{
        alert("save failed!");
      }
    });
  }

  toCCSL(){
    if (!this.isFileExist) {
      return;
    }
    this.ToCCSLEvent.emit(true);
  }

  login(){
		location.href='http://re4cps.org/login'
	}

  safenlCheck(){
    console.time("behavior-time");
    if(!this.isCCSL){
      return;
    }
    this.safenlService.setLayer("SafenlLayer")
    this.safenlService.safenlCheck(this.userName, this.projectName, this.fileService.version).subscribe( consistents => {
      this.fileService.version = consistents.pop().name;
      this.safenlService.setConsistent(consistents);
      if(consistents.length == 0){
        this.safenlConsistent = true;
      }
      console.timeEnd("behavior-time");
    });
  }

  ccslCheck(){
    // if(!this.safenlConsistent){
    //   return;
    // }
    console.time("circle-time"); 
    this.safenlService.setLayer("CCSLLayer")
    console.log(this.projectName);
    this.safenlService.ccslCheck(this.userName, this.projectName, this.fileService.version).subscribe(consistents => {
      this.fileService.version = consistents.pop().name;
      console.log(this.fileService.version);
      var CGs: string[] = [];
      for(let i = 0; i < consistents.length; i ++ ){
        CGs.push(this.projectName + "-CG-" + i);
      }
      var CCGs: string[] = [];
      for(let i = 0; i < consistents.length; i ++ ){
        CCGs.push(this.projectName + "-CCG-" + i);
      }
      this.safenlService.setCG(CGs);
      this.safenlService.setCCG(CCGs);
      var circles: string[] = [];
      for(let i = 0; i < consistents.length; i ++ ){
        circles.push(this.projectName + "-circle-" + i);
      }
      this.safenlService.setCircle(circles);
      this.safenlService.setConsistent(consistents);
      console.timeEnd("circle-time");
    });
    // this.safenlService.getCG(this.userName, this.projectName, this.fileService.version).subscribe(res => {
    //   if(res){
    //     this.safenlService.setCG(this.projectName + "-CG");
    //     this.safenlService.getCCG(this.projectName).subscribe(res => {
    //       if(res){
    //         this.safenlService.setCCG(this.projectName + "-CCG");
    //         this.safenlService.getCircle(this.projectName).subscribe(circles => {
    //           this.safenlService.setCircle(circles);
    //   //         // this.safenlService.getRECCG(this.projectName).subscribe(RECCGs => {
    //   //         //   this.safenlService.setRECCG(RECCGs);
    //             this.safenlService.ccslCheck(this.projectName).subscribe(consistents => {
    //               this.safenlService.setConsistent(consistents);
    //             });
    //   //         // });
    //         });
    //       }
    //     });
    //   }
    // });
  }

  SMTCheck(){
    if(!this.isCCSL){
      return;
    }
    this.smtCheck = true;
    this.SMTEvent.emit(true);
  }

  minUnsat_smt(){
    this.safenlService.setLayer("SMT-MinUnsat")
    this.safenlService.minUnsat_smt(this.userName, this.projectName, this.fileService.version).subscribe( res => {
      var minunsat = new minunsatRes()
      minunsat.name = "consisnt_check_result"
      console.log('type res ->', typeof res)
      console.log('res -> ', res)
      minunsat.inconsistentType = res
      this.safenlService.setConsistRes(minunsat);
    });
  }
  

  // globalInconsistent(){
  //   this.safenlService.setLayer("SMT-MinUnsat")
  //   this.safenlService.minUnsat_smt(this.userName, this.projectName, this.fileService.version).subscribe( res => {
  //     var minunsat = new minunsatRes()
  //     minunsat.name = "global"
  //     minunsat.inconsistent = res
  //     this.safenlService.setGlobalRes(minunsat);
  //   });
  // }

  // partInconsistent(){
  //   this.safenlService.setLayer("SMT-MinUnsat")
  //   this.safenlService.minUnsat_smt(this.userName, this.projectName, this.fileService.version).subscribe( res => {
  //     var minunsat = new minunsatRes()
  //     minunsat.name = "part"
  //     minunsat.inconsistent = res
  //     this.safenlService.setPartRes(minunsat);
  //   });
  // }

  RTCheck(){
    console.time("rt-time");   
    if(!this.isCCSL){
      return;
    }
    this.safenlService.setLayer("RT-Inconsistent")
    this.safenlService.RTCheck(this.userName, this.projectName, this.fileService.version).subscribe( consistents => {
      this.fileService.version = consistents.pop().name;
      var CGs: string[] = [];
      for(let i = 0; i < consistents.length; i ++ ){
        CGs.push(this.projectName + "-CG-" + i);
      }
      var RCGs: string[] = [];
      for(let i = 0; i < consistents.length; i ++ ){
        RCGs.push(this.projectName + "-RCG-" + i);
      }
      this.safenlService.setCG(CGs);
      this.safenlService.setRCG(RCGs);
      this.safenlService.setConsistent(consistents);
      if(consistents.length == 0){
        this.safenlConsistent = true;
      }
      console.timeEnd("rt-time");
    });
    // console.timeEnd("rt-time");
  }

  uploadFile(): void {
    document.getElementById("xmlFile").click();
  }
  uploader: FileUploader = new FileUploader({
    method: "POST",
    itemAlias: "xmlFile",
    autoUpload: false
  });
  // project;

  selectedFileOnChanged(event: any) {
    //console.log(event.target.files);
    var path = event.target.files[0].webkitRelativePath;
    this.projectAddress = path.split("/")[0];
    //console.log('即将调用upload!');
    this.upload();
    // this.addNewItem(this.projectAddress);
  }

  displayText() {
    document.getElementById("SafeNL-p").style.zIndex = "3";
  }

  switchInterface() {
    if (this.editorType == "text") {
      this.editorType = "diagram";
    } else if (this.editorType == "diagram") {
      this.displayText();
      this.editorType = "text";
    }
  }

  // openEOwl() {
  //   //console.log("open");
  //   this.fileService.searchOwl("eowl").subscribe(owls => {
  //     this.owls = owls;
  //     console.log(this.owls);
  //     this.openOwlEvent.emit(owls);
  //   });
  // }

  // openPOwl() {
  //   //console.log("open");
  //   this.fileService.searchOwl("powl").subscribe(pOwls => {
  //     this.pOwls = pOwls;
  //     console.log(pOwls);
  //     this.openPOwlEvent.emit(pOwls);
  //   });
  // }

  step = 1;
  merge() {
    //console.log(this.dg_service.project)
    if (this.step < 3) {
      this.component_choice_service.set_choice_false();
      this.component_choice_service.merge = true;
    }
  }
  upload() {
    
  }

  owlAdd: string;
  powlName: string;
  eowlName: string;
  type: string;

  nodes: string[];
  
  uploadPF(): void {
    document.getElementById("pfFile").click();
  }
}
